package Helper;

import java.io.Console;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Scanner;

public class Helper {
    public static boolean isDev = false;
    private static ArrayList<String> session = new ArrayList<>();

    public static String md5(String str){
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            if( Helper.isDev ){
                e.printStackTrace();
            }
        }
        md5.update(str.getBytes());
        byte[] md5Bytes = md5.digest();
        String res = "";
        for (int i = 0; i < md5Bytes.length; i++){
            int temp = md5Bytes[i] & 0xFF;
            if (temp <= 0XF){
                res += "0";
            }
            res += Integer.toHexString(temp);
        }
        return res;
    }

    public static void clear(){
        int level = 100;
        for( int i = 0 ; i < 100 ; i++ ){
            System.out.println();
        }
    }

    public static String getSession(int i){
        return session.get(i);
    }

    public static void setSession(int i, String val){
        if( session.size()-1 < i ){
            session.add(val);
        }else{
            session.set(i, val);
        }
    }

    public static String getPassword(String info){
        Scanner scanner = new Scanner(System.in);
        Console console = System.console();
        String password;
        if( console == null ){
            System.err.println("你的系统好像不支持密码不回显（这意味着你的密码将显示在屏幕上！）");
            System.out.print(info);
            password = scanner.next();
        }else{
            char[] passArr = console.readPassword(info);
            password = new String(passArr);
        }

        return password;
    }

    public static void waitter(){
        new Scanner(System.in).nextLine();
    }

    public static void exit(){
        System.out.println("再见！");
        System.exit(0);
    }

    public static boolean brancher(String info, boolean defaultChoice){
        boolean result = defaultChoice;

        Scanner scanner = new Scanner(System.in);

        String tipString = defaultChoice ? "[Y/n]: " : "[y/N]: ";
        String choice;
        do {
            System.out.print("\n" + info + tipString);
            choice = scanner.nextLine();
        }while (!choice.equals("") && !choice.matches("[yYnN]")) ;

        if (!choice.equals("")) {
            if (choice.matches("[yY]")) {
                result = true;
            } else {
                result = false;
            }
        }

        return result;
    }

}